import {
	ref
} from 'vue';
import {
	onShow
} from "@dcloudio/uni-app"

import {
	useDishesApis
} from "../../request/dishes.api.js";

import {
	useWishlistApis
} from '../../request/wishlist.api.js';

export const useController = () => {

	const dishesApis = useDishesApis();
	const wishlistApis = useWishlistApis();

	// 标题
	const tip = ref("");
	// 分类索引
	const sideBarIndex = ref(0);
	// 分类菜品列表
	const dishesList = ref([]);

	// 设置分类菜品列表
	async function getDishesList() {
		console.log("sideBarIndex", sideBarIndex.value);
		tip.value = "";
		const idx = sideBarIndex.value;
		let list = [];
		if (idx === 0) {
			// 评分榜
			list = await dishesApis.getDishesList();
			list = list.sort((a, b) => b.avgRating - a.avgRating);
		} else if (idx === -1) {
			tip.value = "大家下周想吃"
			// 想吃榜
			list = await wishlistApis.getWishlist();
			list = list.sort((a, b) => b.wishesCount - a.wishesCount);
		} else if (idx === -2) {
			tip.value = "我下周想吃"
			// 我想吃
			list = await wishlistApis.getMyWishlist();
			list = list.sort((a, b) => b.wishesCount - a.wishesCount);
		} else {
			// 分类查询
			list = await dishesApis.getDishesListByCategoryId(sideBarIndex.value);
		}

		dishesList.value = list;
	}

	function removeFromWishlist(dishesId) {
		return wishlistApis.deleteOneFromDishlist(dishesId);
	}

	async function addToWishlist(dishesId) {
		return wishlistApis.addOneToWishlist(dishesId);
	}

	async function deleteDishes(dishesId) {
		await dishesApis.deleteDishes(dishesId);
		await getDishesList();
	}

	onShow(() => {
		getDishesList();
	});

	return {
		tip,
		sideBarIndex,
		dishesList,

		getDishesList,
		removeFromWishlist,
		addToWishlist,
		deleteDishes,
	}
}